//
//  AppDelegate.swift
//  kano
//
//  Created by Sophia on 2024/8/14.
//

import UIKit
import CoreData
import Toast_Swift
import AppsFlyerLib
import AppTrackingTransparency
import UserNotifications
import IQKeyboardManagerSwift
import Flutter
import FlutterPluginRegistrant
import FacebookCore

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    lazy var flutterEngine = FlutterEngine(name: "my flutter engine")
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
                
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = .white
        window?.makeKeyAndVisible()
        
        
        flutterEngine.run();
        // Connects plugins with iOS platform code to this app.
        GeneratedPluginRegistrant.register(with: self.flutterEngine);
        
        configApp()
        
        //初始化facebook
        ApplicationDelegate.shared.application(
            application,
            didFinishLaunchingWithOptions: launchOptions)
        
        return true
    }
    
    func application(
        _ app: UIApplication,
        open url: URL,
        options: [UIApplication.OpenURLOptionsKey : Any] = [:]
    ) -> Bool {
        ApplicationDelegate.shared.application(
            app,
            open: url,
            sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
            annotation: options[UIApplication.OpenURLOptionsKey.annotation]
        )
        return true
    }
    
    // MARK:
    func applicationDidBecomeActive(_ application: UIApplication) {
      
        AppsFlyerLib.shared().waitForATTUserAuthorization(timeoutInterval: 60)
//        let customUserId = KAUserManager.shared.user.userGid
//        if(customUserId != ""){
            AppsFlyerLib.shared().customerUserID = KAUserManager.shared.user.userGid
            AppsFlyerLib.shared().start()
//        }
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in}
            
        }
    }
}


extension AppDelegate {
    func configApp() {
        NetService.ka_serviceConfig()
        
        KAAFTool.shared
        KAVCManager.setRooterVC()
        
        ToastManager.shared.isQueueEnabled = true
        ToastManager.shared.isTapToDismissEnabled = false
        ToastManager.shared.duration = 3.0
        ToastManager.shared.position = .center
        ToastManager.shared.style.backgroundColor = .black
        
        KALocationManager.shared
        
//        requestNotificationPermissions()
        
        IQKeyboardManager.shared.enable = true
        
        KAUserManager.shared.var_sessionId = "\(Int(Date().timeIntervalSince1970 * 1000))"
        if KAUserManager.appIsFirstInstall() {
            UserDefaults.standard.set(Date(), forKey: "InstallTime")
        }
        //第一次进入Load页
        KAAFTool.logEvent(event: "SKP_Firsttime_loadpage")
        
        Thread.sleep(forTimeInterval: 2)
    }
}


extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func requestNotificationPermissions() {
        let center = UNUserNotificationCenter.current()
        // Request authorization for notifications
        center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
            if let error = error {
                // Handle the error
                print("Error requesting notification permissions: \(error.localizedDescription)")
            }
            if granted {
                print("Notification permissions granted.")
            } else {
                print("Notification permissions denied.")
            }
        }
        // For iOS 10 and later, you must also set the delegate for UNUserNotificationCenter
        center.delegate = self
    }
    
    // Handle notification presentation when the app is in the foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Display the notification alert, badge, and sound
        completionHandler([.alert, .badge, .sound])
    }
    
    // Handle notification response
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
        // Handle the notification response
        let notification = response.notification
        let userInfo = notification.request.content.userInfo
        
        // Perform actions based on the notification content
        print("Received notification with user info: \(userInfo)")
    }
}
